﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Portal.FileSystemData;
using System.IO;

namespace Portal.Modules.ImageBrowser
{
  /// <summary>
  /// Represents the state when the ImageBrowser is in the thumbnail mode.
  /// </summary>
  public partial class StateShowThumbnails : Portal.StateBase.ModuleState
  {
    DataAccessor _dataAccessor;
    CacheAgent _cacheAgent;

    protected void Page_Load(object sender, EventArgs e)
    {
      _dataAccessor = new DataAccessor(Document);
      _cacheAgent = new CacheAgent(_dataAccessor);

      if (_dataAccessor.Config.ThumbnailCount > 0)
        _dataPager.PageSize = _dataAccessor.Config.ThumbnailCount;
      else
        _dataPager.PageSize = int.MaxValue;

      // Show the Breadcrumb only, if there are directories involved.
      if (_dataAccessor.RootDirectory.SubDirCount > 0)
      {
        _breadCrumbDiv.Visible = true;
        CreateBreadCrumbs(_breadcrumb);
      }
      else
        _breadCrumbDiv.Visible = false;

      if(TransitionArgument != null)
      {
        FileWrapper fileWrap = _dataAccessor.RootDirectory.GetFile(TransitionArgument as string);
        if(fileWrap != null)
        {
          int index = fileWrap.Parent.GetFileIndex(fileWrap.Name);
          if(index >= 0)
          {
            int maxCount = _dataAccessor.Config.ThumbnailCount;
            if (maxCount > 0)
            {
              index = ((int)((index) / maxCount)) * maxCount;
              if (index > 0)
                _dataPager.SetPageProperties(index, maxCount, false);
            }
          }
          CurrentPath = fileWrap.Parent.VirtualPath;
        }
      }
    }


    protected void OnDirectoryContentSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
      e.InputParameters["dataAccessor"] = _dataAccessor;
      e.InputParameters["relativePath"] = CurrentPath;
    }

    protected string GetImageUrl(object item)
    {
      return _cacheAgent.GetThumbnailImageUrl(item as FileSystemWrapper);
    }

    protected string GetThumbAreaStyle()
    {
      return "width: " + _dataAccessor.Config.ThumbnailAreaWidth.ToString() + "px;height: " + _dataAccessor.Config.ThumbnailAreaHeight.ToString() + "px";
    }

    protected string GetThumbImgStyle()
    {
      int maxSize = _dataAccessor.Config.ThumbCfg.MaxSize;
      if (_dataAccessor.Config.ThumbCfg.HasShadow)
        maxSize += _dataAccessor.Config.ThumbCfg.ShadowWidth * 2;
      return "height: " + maxSize.ToString() + "px";
    }


    protected string GetImageAction(object item)
    {
      return (item as FileSystemWrapper).IsDirectory ? "ChangeDir" : "Preview";
    }


    protected void OnPictureCommand(object sender, CommandEventArgs e)
    {
      if (e.CommandName == "Preview")
      {
        ProcessEvent((int) StateEvent.ShowPicture, e.CommandArgument);
      }
      else
      {
        CurrentPath = e.CommandArgument as string;
      }
    }

    /// <summary>
    /// The current selected directory.
    /// </summary>
    protected string CurrentPath
    {
      get
      {
        return ViewState["CurrentPath"] as string;
      }
      set
      {
        if (((string)ViewState["CurrentPath"]) != value)
        {
          ViewState["CurrentPath"] = value;
          _thumbnailList.DataBind();
          _breadcrumb.Controls.Clear();
          CreateBreadCrumbs(_breadcrumb);
        }
      }
    }

    private void CreateBreadCrumbs(Control targetCtrl)
    {
      DirectoryWrapper directory;
      if (string.IsNullOrEmpty(CurrentPath))
        directory = _dataAccessor.RootDirectory;
      else
        directory = _dataAccessor.RootDirectory.GetSubDirectory(CurrentPath);

      if (null != directory)
      {
        // Add current directory.
        Literal currLayer = new Literal();
        currLayer.Text = directory.PresentationName;
        targetCtrl.Controls.Add(currLayer);

        // Add all parent directories.
        DirectoryWrapper dir = directory.Parent;
        int step = 0;
        while (dir != null)
        {
          targetCtrl.Controls.AddAt(0, new LiteralControl(" >> "));

          var dirLayer = new LinkButton();
          dirLayer.ID = "DirUp" + step++; // Necessary for a working Eventhandling.
          dirLayer.Text = dir.PresentationName;
          dirLayer.CommandArgument = dir.VirtualPath;
          dirLayer.Command += new CommandEventHandler(OnChangeDir);
          targetCtrl.Controls.AddAt(0, dirLayer);

          dir = dir.Parent;
        }
      }
      else
      {
        string dirNotFound = Portal.Api.Language.GetText(Portal.Api.Module.GetModuleControl(this), "DirectoryNotFound");
        targetCtrl.Controls.AddAt(0, new LiteralControl("<i>" + dirNotFound + "</i>"));
      }
    }

    void OnChangeDir(object sender, CommandEventArgs e)
    {
      CurrentPath = e.CommandArgument as string;
    }


  }
}
